//
//  DuanziViewController.m
//  暴走段子_王桂敏
//
//  Created by 王桂敏 on 15/6/1.
//  Copyright (c) 2015年 lanouhn. All rights reserved.
//

#import "DuanziViewController.h"
#import "Define.h"
#import "LableView.h"
#import "NetWorkEngine.h"
#import "MessageModel.h"
#import "TableViewCell.h"
#import "DetailViewController.h"
#import "LoadingCell.h"
#import "UserViewController.h"
#import "MoviePlayer.h"
#import "UIViewController+MMDrawerController.h"
#import "UMSocial.h"
@interface DuanziViewController ()<NetworkEngineDelegate,LableViewDelegate,UIScrollViewDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,retain) UIScrollView *scrollView;//滚动视图
@property (nonatomic,retain) LableView *lableView;//按钮切换界面视图
@property (nonatomic,retain) NSMutableArray *dataSource;//数据源
@property (nonatomic,retain) NSArray *titles;//标签控制器按钮的title
@property (nonatomic,retain) NSMutableArray *tableViews;//表视图数据
@property (nonatomic,assign) int page;//滚动视图当前的页码
@property (nonatomic,retain) NSArray *URLArray;//网址数组
@property (nonatomic,assign) int pageOfURL;//请求数据的页码
@property (nonatomic,retain) NSMutableArray *refreshArray;//下拉刷新对象数组
@property (nonatomic,retain) NSFileManager *fileManager;//文件管理器，用来做数据持久化
@property (nonatomic,retain) NSMutableArray *dataPathArray;//存放数据的文件路径
@property (nonatomic,retain) UIBarButtonItem *setupButton;//抽屉按钮（设置）
@property (nonatomic,assign) NSIndexPath *indexPath;
@end

@implementation DuanziViewController
- (void)dealloc{
    [_scrollView release];
    [_lableView release];
    [_dataSource release];
    [_titles release];
    [_tableViews release];
    [_URLArray release];
    [_refreshArray release];
    [_fileManager release];
    [_dataPathArray release];
    [_setupButton release];

    [super dealloc];
}
#pragma mark - laze loading -

- (UIBarButtonItem *)setupButton{
    if (!_setupButton) {
        UIImage *image = [UIImage imageNamed:@"icon_fav"];
        self.setupButton = [[[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStyleDone target:self action:@selector(handleSetupAction:)] autorelease];
        

    }
    return _setupButton;
}
- (void)handleSetupAction:(UIBarButtonItem *)sender{
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:^(BOOL finished) {
    }];
}
- (NSMutableArray *)dataPathArray{
    if (!_dataPathArray) {
        self.dataPathArray = [NSMutableArray array];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docPath = paths.lastObject;
        for (int i = 0; i < self.titles.count; i++) {
            NSString *dataPath = [docPath stringByAppendingPathComponent:[NSString stringWithFormat:@"dataSource%d.arc",i]];
            [_dataPathArray addObject:dataPath];
        }
    }
    return _dataPathArray;
}

- (NSFileManager *)fileManager{
    if (!_fileManager) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docPath = paths.lastObject;

        self.fileManager = [NSFileManager defaultManager];
        [_fileManager createDirectoryAtPath:docPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return _fileManager;
}

- (NSArray *)URLArray{
    if (!_URLArray) {

        NSArray *lastURL = @[@"http://m2.qiushibaike.com/article/list/text?count=30&page=%d",@"http://m2.qiushibaike.com/article/list/imgrank?count=30&page=%d",@"http://m2.qiushibaike.com/article/list/video?count=30&page=%d",@"http://m2.qiushibaike.com/article/list/day?count=30&page=%d",@"http://m2.qiushibaike.com/article/list/latest?count=30&page=%d"];
        NSArray *nextURL = @[@"&readarticles=%5B106726574%2C106726180%2C106742180%2C106714808%2C106723566%5D&AdID=1432370670568007B38D95",@"&readarticles=%5B106721170%5D&AdID=1432372042733307B38D95",@"&readarticles=%5B106717370%2C106717768%5D&AdID=1432370830134107B38D95",@"&readarticles=%5B106721662%2C106724284%2C106707600%2C106713472%5D&AdID=1432372354149907B38D95",@"&readarticles=%5B106731328%5D&AdID=1432372516748907B38D95"];
         self.URLArray = @[lastURL,nextURL];
    }
    return _URLArray;
}

- (NSMutableArray *)refreshArray{
    if (!_refreshArray) {
        self.refreshArray = [NSMutableArray array];
        for (int i = 0; i < self.titles.count; i++) {
            UIRefreshControl *refreshControl = [[[UIRefreshControl alloc] init] autorelease];
            refreshControl.tag = 300 + i;
            [refreshControl addTarget:self action:@selector(handleRefreshAction:) forControlEvents:UIControlEventValueChanged];
            [_refreshArray addObject:refreshControl];
        }
    }
    return _refreshArray;
}

- (NSMutableArray *)tableViews{
    if (!_tableViews) {
        self.tableViews = [NSMutableArray array];
        for (int i = 0; i < self.titles.count; i++) {
            UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(kSCREENWIDTH * i, 44, kSCREENWIDTH,kSCREENHEIGHT) style:UITableViewStylePlain];
            tableView.tag = 300 + i;
            //声明表视图的代理对象
            tableView.dataSource = self;
            tableView.delegate = self;

            [tableView registerClass:[TableViewCell class] forCellReuseIdentifier:@"CELL"];//注册单元格
            [tableView registerClass:[LoadingCell class] forCellReuseIdentifier:@"LOADING"];

            [tableView addSubview:self.refreshArray[i]];//给表视图添加下拉刷新控件

            [self.scrollView addSubview:tableView];
            [self.tableViews addObject:tableView];
            [tableView release];
        }
    }
    return _tableViews;
}

- (void)handleRefreshAction:(UIRefreshControl *)refresh{
    self.pageOfURL = 1;
    [self _startLoadingDataWithPage:self.pageOfURL];
}

- (NSArray *)titles{
    if (!_titles) {
        self.titles = @[@"纯文",@"纯图",@"视频",@"精华",@"最新"];
    }
    return _titles;
}

- (LableView *)lableView{
    if (!_lableView) {
        self.lableView = [LableView defaultLableView:self.titles];
        _lableView.frame = CGRectMake(0, 64, CGRectGetWidth([UIScreen mainScreen].bounds), 44);

        [self.view addSubview:_lableView];

    }
    return _lableView;}

- (UIScrollView *)scrollView{

    if (!_scrollView) {
        self.scrollView = [[[UIScrollView alloc] initWithFrame:self.view.bounds] autorelease];
        CGRect frame = _scrollView.frame;
        frame.origin.y = 64;
        _scrollView.frame = frame;
        _scrollView.pagingEnabled = YES;//设置整页翻动
        _scrollView.directionalLockEnabled = YES;//设置定向滑动
        _scrollView.contentSize = CGSizeMake(kSCREENWIDTH * self.titles.count, self.view.bounds.size.height);//设置滚动视图的滚动范围
        _scrollView.tag = 200;
//        _scrollView.canCancelContentTouches = YES;
        _scrollView.backgroundColor = [UIColor clearColor];
        [self.view addSubview:self.scrollView];
    }
    return _scrollView;
}

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        self.dataSource = [NSMutableArray array];
        for (int i = 0; i < self.titles.count; i++) {
            NSMutableArray *array = [NSMutableArray array];
            [_dataSource addObject:array];
        }
    }
    return _dataSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"暴走段子";
    self.view.backgroundColor = [UIColor clearColor];

    self.navigationItem.leftBarButtonItem = self.setupButton;
    self.navigationController.navigationBar.barTintColor = [UIColor orangeColor];

    self.automaticallyAdjustsScrollViewInsets = NO;//默认为YES，设置为NO，添加的表视图就不会被导航条掩盖
    self.scrollView.delegate = self;

    self.lableView.delegate = self;


    NSString *datasourcePath = [self getDoc];

    self.page = 0;
    self.pageOfURL = 1;
    if ([[NSFileManager defaultManager] fileExistsAtPath:datasourcePath]) {
        self.dataSource = [NSKeyedUnarchiver unarchiveObjectWithFile:datasourcePath];
        for (int i = 0; i < 5; i++) {
            [self.tableViews[i] reloadData];
        }
    [self.tableViews[0] reloadData];
    } else {

        [self _startLoadingDataWithPage:self.pageOfURL];
    }

    


}
//加载数据方法
- (void)_startLoadingDataWithPage:(int)pageOfURL
{
//拼接网址的时候发现用Format拼接字符串会对特殊字符进行转换处理，导致出错，但是使用appending是直接拼接，不对数据进行处理
    [self.refreshArray[self.page] beginRefreshing];
    NetWorkEngine *engine =[NetWorkEngine engineWithURL:[NSURL URLWithString:[[NSString stringWithFormat:self.URLArray[0][self.page],self.pageOfURL] stringByAppendingString:self.URLArray[1][self.page]]] parameters:nil delegate:self];
    [engine start];

}

#pragma mark - NetWorkEngine -
//对网上下载的数据进行处理（放在数据源数组中）
- (void)networkDidFinishLoading:(NetWorkEngine *)engine withInfo:(id)info{


    //--------------------------------------------------------------------

    //当请求的是第一页数据时，移除数组中的元素，重新加载数据
    if (self.pageOfURL == 1) {
        [self.dataSource[self.page] removeAllObjects];
    }

    //当请求的不是第一页数据时，在数据源数据中拼接另一页数组
    //--------------------------------------------------------------------
    NSDictionary *data = [NSJSONSerialization JSONObjectWithData:info options:NSJSONReadingMutableContainers error:nil];
    NSArray *items = data[@"items"];


    for (NSDictionary *dic in  items) {
        MessageModel *message = [[MessageModel alloc] initWithDictionary:dic];
        [self.dataSource[self.page] addObject:message];
    }

    
    [self.tableViews[self.page] reloadData];
    [self.refreshArray[self.page] endRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
#pragma mark - UITableViewDataSource -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{


    if (tableView.tag - 300 == self.page) {
        NSLog(@"%lu",[self.dataSource[self.page] count]);
        return [self.dataSource[self.page] count] + 1;

    }

    if ([self.dataSource[tableView.tag - 300] count] == 0) {
        NSLog(@"%lu",[self.dataSource[tableView.tag - 300] count]);
        return 0;
    }
    NSLog(@"%lu",[self.dataSource[tableView.tag - 300] count]);
    return [self.dataSource[tableView.tag - 300] count] + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.row == [self.dataSource[tableView.tag - 300] count] || indexPath.row > [self.dataSource[tableView.tag - 300] count]) {
        LoadingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LOADING" forIndexPath:indexPath];
        return cell;
    }
    MessageModel *message = self.dataSource[tableView.tag - 300][indexPath.row];
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];
    [cell configureWithMessage:message];
    cell.userButton.tag = 100 + indexPath.row;
    [cell.userButton addTarget:self action:@selector(handleUserButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell.forButton addTarget:self action:@selector(handleForButtonAction:) forControlEvents:UIControlEventTouchUpInside];


        return cell;
}

- (void)handleForButtonAction:(UIButton *)sender{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"557bfe6b67e58e83b0004b5e"
                                      shareText:@"你要分享的文字"
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,nil]
                                       delegate:self];
}


#pragma mark - UITableViewDelegate -
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.row == [self.dataSource[tableView.tag - 300] count]) {
        return 44;
    }
    MessageModel *message = self.dataSource[tableView.tag - 300][indexPath.row];

    return message.rowHeight;
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == [self.dataSource[tableView.tag - 300] count]) {
        [(LoadingCell *)cell startLoading];
        self.pageOfURL++;
        [self _startLoadingDataWithPage:self.pageOfURL];

    }

}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{


    self.navigationItem.backBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:[NSString stringWithFormat:@""] style:UIBarButtonItemStylePlain target:nil action:nil] autorelease];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];//设置backBarButton的颜色



    DetailViewController *detail = [[[DetailViewController alloc] initWithContentView:nil message:self.dataSource[tableView.tag - 300][indexPath.row]] autorelease];
    [self.navigationController pushViewController:detail animated:YES];

}

#pragma mark - UIScrollViewDelegate -
//滚动视图滑动结束时执行的操作
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{


    if (scrollView.tag == 200) {
        //设置当前的页码
        self.page = scrollView.contentOffset.x / [UIScreen mainScreen].bounds.size.width;
        //设置通过滑动视图的offset影响按钮的状态
        for (UIButton *button in self.lableView.subviews) {
            if (button.tag - 100 == self.page) {
                [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            } else {
                [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            }
        }

        self.pageOfURL = (int)[self.dataSource[self.page] count] / 30;
        if (self.pageOfURL > 0) {
            return;
        }
        if (self.pageOfURL == 0) {
            self.pageOfURL = 1;
        }


        [self _startLoadingDataWithPage:self.pageOfURL];

    }
}

#pragma mark - LableViewDelegate -
- (void)actionWithButton:(UIButton *)sender{

    self.scrollView.contentOffset = CGPointMake([UIScreen mainScreen].bounds.size.width * (sender.tag - 100), 0);
    self.page = (int)sender.tag - 100;


    for (UIButton *button in self.lableView.subviews) {
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    }
    [sender setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    self.pageOfURL = (int)[self.dataSource[self.page] count] / 30;
    if (self.pageOfURL > 0) {
        return;
    }
    if (self.pageOfURL == 0) {
        self.pageOfURL = 1;
    }
    [self _startLoadingDataWithPage:self.pageOfURL];

    
}



- (void)handleUserButtonAction:(UIButton *)sender{



    UserViewController *userVC = [[UserViewController alloc] initWithUser_id:[(UserModel *)[self.dataSource[self.page][sender.tag - 100] user] uid]];

    UILabel *naviTitleLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 200, 44)];
    naviTitleLable.text = [(UserModel *)[self.dataSource[self.page][sender.tag - 100] user] login];
    naviTitleLable.textColor = [UIColor whiteColor];
    naviTitleLable.textAlignment = NSTextAlignmentCenter;
    naviTitleLable.font = [UIFont systemFontOfSize:15];
    userVC.navigationItem.titleView = naviTitleLable;


    [self.navigationController pushViewController:userVC animated:YES];
    [userVC release];
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{

    MoviePlayer *player = [MoviePlayer defaultMoviePlayer];
    [player.view removeFromSuperview];
    [player stop];

}

- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:YES];
//    NSFileManager *filemanager = [NSFileManager defaultManager];//创建文件管理器
    NSString *cachePath = [self getDoc];
    NSString *datasourcePath = [cachePath stringByAppendingPathComponent:@"datasource.dz"];
    //使用归档对象，归档对应的数据
    [NSKeyedArchiver archiveRootObject:self.dataSource toFile:datasourcePath];
    
}

//获取缓存路径
- (NSString *)getDoc{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *docPath = paths.lastObject;

    return docPath;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
